<template>
  <div class="resumeItemContainer">
    <div class="resumeItemTitle">
      <div class="resumeItemTitleFlag"></div>
      <span class="resumeItemTitleContent">求职意向</span>
      <span class="resumeItemTitleAddIcon" @click="handleAddClick" v-show="resumeDataList.length<3">
        <img :src="resumeItemAddIcon" class="resumeItemAddIcon"> 添加
      </span>
    </div>
    <div class="resumeItemMain">
      <div class="resumeItemDisplayList">
        <div class="resumeItemDisplayItem" v-for="aimItem,index in resumeDataList" :key="aimItem.intended_id">
          <div class="resumeItemDisplayItemEditButtons">
            <template v-if="!aimItem.editStatus">
              <span class="resumeItemDisplayItemEditButton" @click="changeEditStatus(aimItem,true)">
                <img :src="myResumeEditIcon" /> 编辑</span>
              <span class="resumeItemDisplayItemEditButton" @click="handleDeletClick(aimItem)"
                v-show="resumeDataList.length>1">
                <img :src="myResumeDeleteIcon" />删除</span>
            </template>
          </div>
          <div class="displayBlock" v-if="!aimItem.editStatus">
            <!-- 非编辑状态 -->
            <span class="bold"> {{aimItem.zwname}} </span>
            <span class="divide" v-if="aimItem.salary_str"></span>
            <span class="bold"> {{aimItem.salary_str}}</span>
            <span class="divide" v-if="aimItem.cityName"></span>
            <span> {{aimItem.cityName}}</span>
            <span class="divide" v-if="aimItem.tradeName"></span>
            <span> {{aimItem.tradeName}}</span>
          </div>
          <div class="editBlock" v-else :id="aimItem.editStatus?'edittingBlock':''">

            <div class="resumeItemEdit">
              <el-form :ref="'editForm'+aimItem.intended_id" :model="aimItem.editForm" inline :rules="rules"
                :key="aimItem.intended_id">
                <el-form-item label="期望行业" prop="tradeid">
                  <el-cascader ref="aimInfo_tradeid_cascader"
                    :visible.sync="cascaderVisibleStates.aimInfo_tradeid_cascader" v-model="aimItem.editForm.tradeid"
                    filterable :options="tradeList" key="tradeInfo" :props="cascaderProps" :emitPath="true"
                    @change="(e)=>{handleCascaderChange(e,aimItem,'tradeInfo')}" :style="{width:'100%'}" clearable
                    placeholder="请选择期望行业" />
                </el-form-item>
                <el-form-item label="意向职位" prop="zwid">
                  <el-cascader ref="aimInfo_zwid_cascader" :visibile.sync="cascaderVisibleStates.aimInfo_zwid_cascader"
                    v-model="aimItem.editForm.zwid" filterable :options="aimItem.positionList"
                    :key="aimItem.positionList&&aimItem.positionList.length"
                    :props="{...cascaderProps,value:'selfId',label:'selfName',children:'children'}" :emitPath="true"
                    @change="(e)=>{handleCascaderChange(e,aimItem,'positionInfo')}" :style="{width:'100%'}" clearable
                    placeholder="请选择意向职位" />
                </el-form-item>
                <el-form-item label="意向城市" prop="intended_city">
                  <el-cascader ref="aimInfo_intended_city_cascader"
                    :visivle.sync="cascaderVisibleStates.aimInfo_intended_city_cascader" v-model="aimItem.intended_city"
                    filterable :options="regionData" key="cityInfo" :props="cascaderProps"
                    @change="(e)=>{handleCascaderChange(e,aimItem,'cityInfo')}" :style="{width:'100%'}" clearable
                    placeholder="请选择意向城市" />
                </el-form-item>
                <el-form-item label="期望月薪" prop="min_salary">
                  <el-input v-model="aimItem.editForm.min_salary" placeholder="请输入期望月薪" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="求职类型" prop="jobInfo">
                  <el-select v-model="aimItem.editForm.jobInfo" placeholder="请选择求职类型"
                    @change="(e)=>{handleCascaderChange(e,aimItem,'jobInfo')}">
                    <el-option v-for="item in resumeTypeList" :key="item.value" :label="item.label"
                      :value="item.label+'-'+item.value">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <div class="submitButtons">
                    <el-button size="small" @click="handleCancelForItem(aimItem)">取 消</el-button>
                    <el-button size="small" type="primary" @click="handleSaveForItem(aimItem)">完 成</el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>
<script>
import myResumeItemsMixin from "@/mixin/myResumeItemsMixin.js";
import { findObjectBySixDigitValue } from "@/utils/regionTools";
import { resumeTypeList } from "@/utils/resumeData";
import tradeList from "@/utils/tradeData";
import { region } from "@/components/SelectRegion/region.js";
export default {
  name: "aimInfo",
  mixins: [myResumeItemsMixin],
  props: {
    resumeData: {
      type: Array,
      default: () => [],
    },
    editStatus: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      regionData: region,
      tradeList,
      resumeTypeList,
      resumeDataList: [], //
      positionList: [], //
      cascaderProps: {
        checkStrictly: true, // 严格检查，不自动勾选父级
        value: "value",
        label: "label",
        children: "children",
        emitPath: false, // 不返回完整的路径，只返回最终选中的值
      },
      rules: {
        tradeid: [
          { required: true, message: "请选择期望行业", trigger: "change" },
        ],
        zwid: [
          { required: true, message: "请选择意向职位", trigger: "change" },
        ],
        intended_city: [
          { required: true, message: "请选择意向城市", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    resumeData: {
      immediate: true,
      handler(newValue, oldValue) {
        //console.log("求职意向aimInfo基本信息更新：", newValue);
        if (newValue) {
          this.resumeDataList = newValue.map((aimItem, index) => {
            //在没有这些参数的时候才会追加
            if (!aimItem.hasOwnProperty("editStatus")) {
              this.$set(aimItem, "editStatus", false);
            }
            if (!aimItem.hasOwnProperty("positionList")) {
              this.$set(aimItem, "positionList", []);
            }
            if (!aimItem.hasOwnProperty("editForm")) {
              if (aimItem.jobtype && aimItem.jobtype_str) {
                var jobInfo = aimItem.jobtype_str + "-" + aimItem.jobtype;
              } else {
                var jobInfo = "";
              }

              this.$set(aimItem, "editForm", {
                tradeid: aimItem.tradeid,
                tradeName: aimItem.tradeName,
                zwid: aimItem.zwid,
                zwname: aimItem.zwname,
                intended_city: aimItem.intended_city,
                intended_cityName: aimItem.cityName,
                jobInfo,
                min_salary: aimItem.min_salary,
                parentid: aimItem.parentid,
                intended_id: aimItem.intended_id,
              });
            }
            return aimItem;
          });
        }
      },
    },
    editStatus: {
      handler(newValue, oldValue) {
        //如果新值是false要把所有的editStatus改为false
        if (newValue == false) {
          this.resumeDataList.forEach((item) => {
            item.editStatus = false;
            if (item.isNew) {
              this.resumeDataList.splice(this.resumeDataList.indexOf(item), 1);
            }
          });
        }
      },
    },
  },
  methods: {
    //根据行业获取职位类型
    async reqGetPositionType(aimItem) {
      const finalParams = {
        op: "person_intended_industry_busi",
        func: "getTradeZwCache",
        version: "v7.8.0",
        forName: "iphone",
        person_id: this.personId,
        param: {
          tradeid: aimItem.editForm.tradeid,
        },
      };
      this.resumeGeneralInterface(
        finalParams,
        (res) => {
          //console.log("获取职位类型成功", res);
          this.$set(aimItem, "positionList", res.data);
          //console.log("potitionList", aimItem);
        },
        () => {}
      );
    },
    //保存
    async handleSaveForItem(aimItem) {
      this.$refs["editForm" + aimItem.intended_id][0].validate((valid) => {
        if (valid) {
          const finalParams = {
            op: "person_intended_industry_busi",
            func: "updateIntendedTrade",
            version: "v7.2.8",
            forName: "iphone",
            person_id: this.personId,
            param: {
              person_id: this.personId,
              param: {
                tradeid: aimItem.editForm.tradeid,
                tradeName: aimItem.editForm.tradeName,
                zwid: aimItem.editForm.zwid,
                zwname: aimItem.editForm.zwname,
                intended_city: aimItem.editForm.intended_city,
                intended_cityName: aimItem.editForm.intended_cityName,
                min_salary: aimItem.editForm.min_salary,
                jobtype: aimItem.editForm.jobtype,
                jobtypeName: aimItem.editForm.jobtypeName,
              },
            },
          };

          if (aimItem.isNew) {
            finalParams.func = "addIntendedTrade";
          } else {
            //修改的时候才有
            finalParams.param.param.intended_id = aimItem.editForm.intended_id;
            finalParams.param.param.parentid = aimItem.editForm.parentid;
          }
          //console.log("修改求职意向：", finalParams);
          this.resumeGeneralInterface(
            finalParams,
            () => {
              this.changeEditStatus(aimItem, false);
              aimItem.isNew = false;
              this.$emit("reqGetIntenedInfo");
            },
            () => {}
          );
        } else {
          //console.log("error submit!!");
        }
      });
    },
    handleCancelForItem(aimItem) {
      this.changeEditStatus(aimItem, false);
      //取消要复原表单数据

      if (aimItem.isNew) {
        this.resumeDataList.splice(this.resumeDataList.indexOf(aimItem), 1);
      } else {
        if (aimItem.jobtype && aimItem.jobtype_str) {
          var jobInfo = aimItem.jobtype_str + "-" + aimItem.jobtype;
        } else {
          var jobInfo = "";
        }
        this.$set(aimItem, "editForm", {
          tradeid: aimItem.tradeid,
          tradeName: aimItem.tradeName,
          zwid: aimItem.zwid,
          zwname: aimItem.zwname,
          intended_city: aimItem.intended_city,
          intended_cityName: aimItem.cityName,
          jobInfo,
          min_salary: aimItem.min_salary,
          parentid: aimItem.parentid,
          intended_id: aimItem.intended_id,
        });
      }
    },
    handleCascaderChange(value, aimItem, prop) {
      if (!value) {
        return;
      }
      switch (prop) {
        case "tradeInfo":
          const tradeItem = this.findItemForTrade(this.tradeList, value);
          aimItem.editForm.tradeid = tradeItem.value;
          aimItem.editForm.tradeName = tradeItem.label;
          this.reqGetPositionType(aimItem);
          break;
        case "cityInfo":
          const city = findObjectBySixDigitValue(value, this.regionData);
          aimItem.editForm.intended_city = city.value;
          aimItem.editForm.intended_cityName = city.label;
          break;
        case "jobInfo":
          const job = value.split("-");
          aimItem.editForm.jobtype = job[1];
          aimItem.editForm.jobtypeName = job[0];
          break;
        case "positionInfo":
          aimItem.editForm.zwid = value;
          aimItem.editForm.zwname = this.findZwName(
            aimItem.positionList || [],
            value
          );

        default:
          break;
      }
    },
    findZwName(array, zwid) {
      for (const item of array) {
        if (item.selfId === zwid) {
          //console.log("找到了zwname", item.selfName);
          return item.selfName; // 返回自定义的selfName
        } else if (item.children) {
          const result = this.findZwName(item.children, zwid);
          if (result) {
            return result; // 返回找到的selfName
          }
        }
      }
      return undefined;
    },
    handleDeletClick(aimItem) {
      this.$confirm("确定删除该条求职意向吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //下面才是删除方法
          const finalParams = {
            op: "cma_weixin_deal",
            func: "updataObjColumn",
            forName: "iphone",
            param: {
              person_id: this.personId,
              conditionArr: {
                delIntended: aimItem.intended_id,
              },
            },
          };
          this.resumeGeneralInterface(
            finalParams,
            () => {
              this.$emit("reqGetIntenedInfo");
            },
            () => {}
          );
        })
        .catch(() => {});
    },
    handleCancelClick(aimItem) {
      this.changeEditStatus(aimItem, false);
    },
    //因为要发送请求，所以不放进mixin中
    changeEditStatus(aimItem, status) {
      //意向职位列表是通过接口获取的，为了复现需要在展示表格的时候就获取
      if (
        status == true &&
        !(aimItem.positionList && aimItem.positionList.length)
      ) {
        this.reqGetPositionType(aimItem);
      }

      //当想设置editStatus为true时，检查resumeList是否已经有正在编辑的项目，如果有就弹出提示框
      if (status) {
        let editingIndex = this.checkEditingItem();
        if (editingIndex != -1) {
          this.$confirm("有内容没有保存，确定退出编辑吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              //全部关闭编辑再打开当前的
              this.resumeList.forEach((item) => {
                item.editStatus = false;
              });
              this.resumeDataList.forEach((item) => {
                item.editStatus = false;
              });
              this.$emit("update:editStatus", status);
              aimItem.editStatus = status;
            })
            .catch(() => {});
        } else {
          this.$emit("update:editStatus", status);
          aimItem.editStatus = status;
        }
      } else {
        //如果是设置为false则直接设置当前的状态
        this.$emit("update:editStatus", status);
        aimItem.editStatus = status;
      }
    },
    //在两层结构中的tradeData中找到对应的tradeName
    findItemForTrade(arr, value) {
      for (let item of arr) {
        if (item.value === value) {
          //console.log("找到了result", item);
          return item; // 直接返回找到的项
        } else if (item.children) {
          const foundItem = this.findItemForTrade(item.children, value); // 递归查找子项
          if (foundItem) {
            // 如果在子项中找到了匹配项，返回该项
            return foundItem;
          }
        }
      }
      return null; // 如果没有找到匹配项，返回null
    },
  },
};
</script>

<style lang="scss" scoped>
.resumeItemContainer {
  display: flex;
  flex-direction: column;
  margin: 20px 0 16px;
  .resumeItemTitle {
    display: flex;
    align-items: center;
    .resumeItemTitleFlag {
      width: 4px;
      height: 19px;
      background: #0b6eff;
      border-radius: 2px;
      margin-right: 10px;
    }
    .resumeItemTitleContent {
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 20px;
      color: #333333;
      margin-right: 19px;
    }
    .resumeItemTitleAddIcon {
      display: flex;
      align-items: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #4880ff;
      cursor: pointer;
      .resumeItemAddIcon {
        width: 20px;
        height: 20px;
        margin-right: 8px;
      }
    }
  }
  .resumeItemMain {
    margin-top: 16px;
    .resumeItemDisplayList {
      .resumeItemDisplayItem {
        position: relative;
        margin-bottom: 18px;
        &:last-of-type {
          margin-bottom: 0px;
        }
        &:hover {
          .displayBlock {
            background: #f8f8f8;
            border-radius: 8px;
            padding: 16px;
          }
          .resumeItemDisplayItemEditButtons {
            display: block;
          }
        }
        .resumeItemDisplayItemEditButtons {
          display: none;
          position: absolute;
          top: -18px;
          right: 0;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 15px;
          color: #4880ff;
          line-height: 18px;
          & > span {
            display: inline-flex;
            align-items: center;
            cursor: pointer;
            margin-left: 23px;
            user-select: none;
            & > img {
              width: 16px;
              height: 16px;
              margin-right: 5px;
            }
          }
        }
        .displayBlock {
          display: flex;
          align-items: center;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 15px;
          color: #666666;
          line-height: 18px;
          text-align: left;
          font-style: normal;
          .bold {
            font-weight: bold;
            font-size: 15px;
            color: #000000;
            line-height: 21px;
          }
          .divide {
            width: 1px;
            height: 11px;
            background: #cccfd7;
            margin: 0 12px;
          }
        }
        .editBlock {
          margin-top: 2px;
          background: #f8f8f8;
          border-radius: 8px;
          padding: 16px;
          ::v-deep .el-form-item {
            display: inline-flex;
            flex-direction: column;
            min-width: 251px;
            width: calc(33% - 40px);
            margin-right: 24px;
            margin-bottom: 16px;
            margin-top: 0px;
            .el-form-item__label {
              height: 22px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 14px;
              color: #666660;
              line-height: 20px;
              text-align: left;
              font-style: normal;
            }
          }
          .submitButtons {
            display: flex;
            justify-content: flex-end;
            position: relative;
            top: 24px;
            right: 0;
            .el-button {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 100px;
              height: 30px;
              background: #ffffff;
              border-radius: 4px;
              border: 1px solid #cdcdcd;
              font-family: PingFang-SC, PingFang-SC;
              font-weight: bold;
              font-size: 14px;
              text-align: left;
              font-style: normal;
              padding: 0;
              &.el-button--primary {
                width: 100px;
                height: 30px;
                background: #4880ff;
                border-radius: 4px;
              }
            }
          }
        }
      }
    }
  }
}
</style>